/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package rdfparser.parser;

import java.io.File;
import java.io.IOException;
import java.net.URLDecoder;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import rdfparser.util.FileDirectoryHandler;

/**
 *
 * @author Amendra Shrestha
 */
public class ParserHandler extends DefaultHandler {

    /**
     * decodes the filename as file URL renames the file taking the last part of
     * full file name parsed the renamed file to matching parser
     *
     * @param baseDir
     * @param fileDir
     * @param fileName
     * @return boolean
     */
    public boolean parseDocument(String fileName) {
        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser parser;
        try {
            // decode file to get rid of unusual characters
            String decodedFileURL = URLDecoder.decode(fileName, "UTF-8");
            // get last part of decoded url which will be the new file name to be renamed
            String newFileName = decodedFileURL.substring(decodedFileURL.lastIndexOf("?") + 1, decodedFileURL.length());
            // rename the file and return the same file which needs to be parse
            File fileToParse = FileDirectoryHandler.renameFile(fileName, newFileName);

            parser = spf.newSAXParser();
            // parse file
            parser.parse(fileToParse, this);
            return true;
        } catch (ParserConfigurationException e) {
            System.out.println("ParserConfigurationException in ParserHandler: " + e);
            return false;
        } catch (SAXException e) {
            System.out.println("SAXException in ParserHandler: " + e);
            return false;
        } catch (IOException e) {
            System.out.println("IOException in ParserHandler: " + e);
            return false;
        }
    }
}
